package com.ccz.demo.bookdemo.javayibubianchengshizhan.c2;

/**
 * @ClassName SyncExample
 * @Author caihaoyun
 * @Date 2020/5/26
 * @Version V1.0
 * 同步编程模型下，在一个线程中要做两件事情的代码是怎样的
 **/
public class SyncExample2_1 {

    public static void doSomethingA() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("--- doSomethingA---");
    }

    public static void doSomethingB() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("--- doSomethingB---");
    }

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        // 同步
        /*{

            // 1.执行任务A
            doSomethingA();
            // 2.执行任务B
            doSomethingB();
            System.out.println(System.currentTimeMillis() - start);
        }*/
        // 异步 实现java.lang.Runnable接口的run方法
        /*{
            // 1.开启异步单元执行任务A
            Thread thread = new Thread(() ->{
                doSomethingA();
            }, "threadA");
            thread.start();
            // 2.执行任务B
            doSomethingB();
            // 3.同步等待线程A运行结束
            thread.join();
            System.out.println(System.currentTimeMillis() - start);
        }*/

        {
            Thread thread = new Thread("threadA"){
                @Override
                public void run() {
                    doSomethingA();
                }
            };
            thread.start();
            // 2.执行任务B
            doSomethingB();
            // 3.同步等待线程A运行结束
            thread.join();
            System.out.println(System.currentTimeMillis() - start);
        }
    }

}
